package com.songlanyun.modules.goods.controller.api;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.songlanyun.common.enums.GoodsConstant;
import com.songlanyun.common.enums.HouniaoConstant;
import com.songlanyun.common.kqUtils.InitOrder;
import com.songlanyun.common.utils.HouniaoApiUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.songlanyun.common.annotation.SysLog;
import com.songlanyun.common.enums.HouniaoConstant;
import com.songlanyun.common.utils.HouniaoApiUtil;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.R;
import com.songlanyun.modules.account.controller.common.AbstractApiController;
import com.songlanyun.modules.category.service.SystemProductCategoryService;
import com.songlanyun.modules.goods.entity.Goods;
import com.songlanyun.modules.goods.entity.GoodsAuthShop;
import com.songlanyun.modules.goods.entity.GoodsContent;
import com.songlanyun.modules.goods.entity.GoodsSku;
import com.songlanyun.modules.goods.model.vo.GoodsSkuComVo;
import com.songlanyun.modules.goods.model.vo.GoodsSlimVo;
import com.songlanyun.modules.goods.model.vo.SkuComItemVo;
import com.songlanyun.modules.goods.service.GoodsAuthShopService;
import com.songlanyun.modules.goods.service.GoodsContentService;
import com.songlanyun.modules.goods.service.GoodsService;
import com.songlanyun.modules.goods.service.GoodsSkuService;
import com.songlanyun.modules.singlegoods.entity.ProductSingleGoodsEntity;
import com.songlanyun.modules.singlegoods.service.ProductSingleGoodsService;
import com.songlanyun.modules.skus.entity.ProductSkusEntity;
import com.songlanyun.modules.skus.service.ProductSkusService;
import com.songlanyun.modules.singlegoods.dao.ProductSingleGoodsDao;
import com.songlanyun.modules.singlegoods.entity.ProductSingleGoodsEntity;
import com.songlanyun.modules.singlegoods.service.ProductSingleGoodsService;
import com.songlanyun.modules.skus.entity.ProductSkusEntity;
import com.songlanyun.modules.skus.service.ProductSkusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * 商品前端通用接品
 *
 */
@RestController
@RequestMapping("api/goods")
public class GoodsApiController extends AbstractApiController {
    @Autowired
    private GoodsContentService goodsContentService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsAuthShopService goodsAuthShopService;

    @Autowired
    private GoodsSkuService goodsSkuService;

    @Autowired
    private HouniaoApiUtil houniaoApiUtil;

    @Autowired
    private ProductSingleGoodsService productSingleGoodsService;


    @Autowired
    private SystemProductCategoryService systemProductCategoryService;


    @Autowired
    private ProductSkusService productSkusService;

    /**
     *  显示商品（注意如果商品没有审核通过，要做体验处理）
     */
    @RequestMapping("/info/{goodsId}")
    public R getById(@PathVariable("goodsId") Long goodsId){
        Goods goods = goodsService.getById(goodsId,true);
        goods.loadResidualInventory();//计算总库存
        return R.ok().put("data", goods);
    }

    /**
     *  显示商品内容
     */
    @RequestMapping("/content/{goodsId}")
    public R getContentById(@PathVariable("goodsId") Long goodsId){
        GoodsContent content = goodsContentService.getByGoodsId(goodsId);
        return R.ok().put("data", content);
    }


    /**
     *
     * 这里会涉及到
     * 商品封面图片
     * 商品售价价格（最低，最高）
     * 库存（总库存，与规格库存）
     * 商品规格表
     * 商品规格项
     * 商品当前限购
     * @param goodsId
     * @return
     */
    @RequestMapping("/skus/{shopId}/{goodsId}")
    public R getGoodsSkuListById(@PathVariable("shopId") Long shopId,@PathVariable("goodsId") Long goodsId){
        GoodsSkuComVo goodsSkuComVo = new GoodsSkuComVo();

        Goods goods = goodsService.getById(goodsId);
        goodsSkuComVo.setGoods(goods);
        goodsSkuComVo.setCurrentShopId(goods.getShopId());
        if(shopId>0)
        {
            goodsSkuComVo.setCurrentShopId(shopId);
        }

        //获得商品的sku集合给移动端
        List<SkuComItemVo> list = goods.loadResidualInventory();
        goodsSkuComVo.setGoodsSkuList(list);
        goodsSkuComVo.setTotalStock(goods.getResidualInventory());


        /**
         * 获取经营权限
         * 可以获知，1是否是代锁，2，是否上架，3，是否审核通过
         */


        GoodsAuthShop auth  = goodsAuthShopService.getAuthorizeInfo(goodsSkuComVo.getCurrentShopId(),goodsId);
        goodsSkuComVo.setGoodsAuth(auth);

        return R.ok().put("data", goodsSkuComVo);
    }



    /**
     *  处理商品的经营权限
     */
    @RequestMapping("/auth/{shopId}/{goodsId}")
    public R getGoodsAuth(@PathVariable("shopId") Long shopId,@PathVariable("goodsId") Long goodsId){
        GoodsAuthShop auth = this.loadGoodsAuthByShop(goodsId,shopId);
        return R.ok().put("data", auth);

    }

    /**
     * 在当前请求环境下加载商品的经营权限
     * @param goodsId
     * @param shopId
     * @return
     */
    private GoodsAuthShop loadGoodsAuthByShop(Long goodsId,Long shopId)
    {
        GoodsAuthShop auth = new GoodsAuthShop();
        /**
         *  小程序用
         *  处理商品的经营权限
         *  1、如果auth数据为null，说明没有经营权限（建议和没审核通过一样处理）
         *  2、如果added上架数据为false，说明现在是下架状态，当前页，显示商品已下架（不能出现购买和加入购物车）
         */
        if(isApplet())
        {
            //查询商品某个店铺的经营权限
            auth = goodsAuthShopService.getAuthorizeInfo(shopId,goodsId);
        }

        /**
         *  App 用
         *  1、如果auth数据为null，说明没有经营权限（建议和没审核通过一样处理）
         *  2、如果added上架数据为false，说明现在是下架状态，当前页，显示商品已下架（不能出现购买和加入购物车）
         */
        if(isApp())
        {
            //查询某个商品店直营权限
            auth = goodsAuthShopService.getDirectSaleAuthorizeInfo(goodsId);
        }
        return auth;
    }



    /**
     * 小程序
     * 在商家店铺中显示商品列表
     * 商家店铺中商品列表(包括代销的平台商品)
     * 注意，如果当前会员是隶属当前店铺，当前店铺的代销产品也要显示，否则不显示当前代销商品
     *
     * APP
     * 在商家店铺中显示商品列表
     * 商家店铺中商品列表(直显示直销商品，不包括代销的平台商品)
     */
    @RequestMapping("/shop/pages/{shopId}")
    public R shopGoodsList(@PathVariable("shopId") Long shopId,@RequestParam Map<String, Object> params){
        params.put("shop_id",shopId);
        params.put("client",getClient());
        params.put("user_id",getUserId(false));
        PageUtils page = goodsService.queryShopPage(params);
        return R.ok().put("page", page);
    }


    /**
     *
     * APP显示积分商品列表
     */
    @RequestMapping("/pointgoods/pages")
    public R pointGoodsGage(@RequestParam Map<String, Object> params){
        PageUtils page = goodsService.pointGoodsGage(params);
        return R.ok().put("page", page);
    }


    /**
     * 小程序
     * 在商家店铺中显示推荐，热门，新品，自营商品
     * type = recommend，hot,new
     * limit= 数量
     *
     * APP
     * 在商家店铺中显示商品列表
     * 商家店铺中商品列表(直显示直销商品，不包括代销的平台商品)
     */
    @RequestMapping("/list/{shopId}")
    public R showGoodsList(@PathVariable("shopId") Long shopId,@RequestParam Map<String, Object> params){
        params.put("shop_id",shopId);
        Integer limit = MapUtil.getInt(params, "limit");
        if(limit==null)
        {
            params.put("limit",8);
        }
        PageUtils list =  goodsService.newAddedGoodsList(params);
        return R.ok().put("list", list);
    }

    /**
     * 从全平台筛选新上架商品(或热门推荐商品)
     * type = recommend，hot,new
     * limit= 数量
     * @param params
     * @return
     */
    @GetMapping("/new")
    public R newAddedGoodsList(@RequestParam Map<String, Object> params){
        Integer limit = MapUtil.getInt(params, "limit");
        if(limit==null)
        {
            params.put("limit",6);
        }
        PageUtils list =  goodsService.newAddedGoodsList(params);
        return R.ok().put("list", list);
    }


    /**
     * 从全平台筛选月销量高的商品列表
     * mixNum=最小展示条目数
     * limit= 数量
     * @param params
     * @return
     */
    @RequestMapping("/month")
    public R monthSaleGoodsList(@RequestParam Map<String, Object> params){
        Integer limit = MapUtil.getInt(params, "limit");
        Integer mixNum = MapUtil.getInt(params, "mix_num");
        if(limit==null)
        {
            limit = 12;
        }
        if(mixNum==null)
        {
            mixNum = 3;
        }

        List<GoodsSlimVo> list =  goodsService.monthSaleGoodsList(limit,mixNum);
        return R.ok().put("list", list);
    }

    /**
     * 从全平台筛选 猜你喜欢
     * @return
     */
    @RequestMapping("/smart")
    public R smartRecommend(@RequestParam Map<String, Object> params){
        PageUtils page =  goodsService.randRecommend(params);
        if(page.getCurrPage()==1) {
            params.put("limit", 30);
            List<GoodsSlimVo> list = goodsService.smartRecommend(params);
            if (list.size() % 2 != 0) {
                list = list.subList(0, list.size() - 2);
            }
            list.addAll((List<GoodsSlimVo>) page.getList());
            page.setList(list);
        }

        return R.ok().put("page", page);
    }





    /**
     * APP
     * 在商家店铺中显示服务商品数量
     */
    @RequestMapping("/count/{shopId}")
    public R showGoodsCount(@PathVariable("shopId") Long shopId,@RequestParam Map<String, Object> params){
        params.put("shop_id",shopId);
        Integer count =  goodsService.loadCount(params);
        return R.ok().put("data", count);
    }

    /**
     * 分页查询全平台商品
     * @param params 查询参数，包含以下几个参数：
     *               houniao_level1_category_id 候鸟的一级分类ID
     *               category_id 惠选系统的商品分类ID
     *               title 商品的关键字
     *               limit 分页查询时每页的最大记录数
     *               page 分页查询时的页码
     * @return 查询到的所有商品
     */
    @RequestMapping("/all/pages")
    public R allPlatformPage(@RequestParam Map<String, Object> params){
        PageUtils page = goodsService.allPlatformPage(params);
        return R.ok().put("page", page);
    }

    /**
     *候鸟商品添加
     * @return
     */
    @GetMapping("/add/{currentPage}")
    public R add(@PathVariable("currentPage") Integer currentPage,@RequestParam(required = false) String tradeTypeId) {
        goodsService.addHouniaoGoods(currentPage,tradeTypeId);
        return R.ok();
    }

    /**
     * 测试方法
     */
    @GetMapping("/testPay")
    public R startPay() {
        BigDecimal amount = BigDecimal.valueOf(0.01);
        String result = InitOrder.gateWayInitOrder(amount,"testcode1234","W2","testgoodsdetails");
        return R.ok().put("data", JSONObject.parseObject(result));
    }


    /**
     * 测试方法
     */
    @GetMapping("/testPay2")
    public R startPay2() {
        BigDecimal amount = BigDecimal.valueOf(0.01);
        String result = InitOrder.gateWayInitOrder(amount,"testcode2345","A2","testgtrtsdetails");
        return R.ok().put("data", JSONObject.parseObject(result));
    }

    @PostMapping("/testPay3")
    public R startPay3(@RequestParam(required = false) String coin){
        System.out.println(coin);
        return R.ok().put("data",coin);
    }


}
